package com.norma.netty.study.nio;

import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author zhangchaofeng
 * @date 2020/10/2
 * @description 多人运动系统服务端
 */
public class GroupChatServer {

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private static final int PORT = 6667;

    public GroupChatServer() {
        try {
            //获取选择器
            selector = Selector.open();
            //获取服务器端channel
            serverSocketChannel = ServerSocketChannel.open();
            //绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            serverSocketChannel.configureBlocking(false);
            //注册到Selector并监听注册事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            listenHandler();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听处理
     */
    public void listenHandler() {
        try {
            //循环处理
            while (true) {
                //监听 1s
                int select = selector.select();
                if (select > 0) {
                    //有时间处理
                    //遍历得到的selectionKeys集合
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        //取出selectionKey
                        SelectionKey key = keyIterator.next();
                        //监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            //设为非阻塞
                            socketChannel.configureBlocking(false);
                            //将该socketChannel注册到selector
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "上线了~");
                        }
                        //读事件
                        if (key.isReadable()) {
                            readData(key);
                        }
                        //将当前的selectionKey删除，防止重复操作
                        keyIterator.remove();
                    }
                } else {
                    System.out.println("等待客户端连接...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

    }

    @SneakyThrows
    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            //通过selectionKey拿到socketChannel
            channel = (SocketChannel) key.channel();
            //创建Buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = channel.read(byteBuffer);
            if (read > 0) {
                //把缓冲区的数据转成字符串
                String msg = new String(byteBuffer.array());
                System.out.println("服务端接受到" + channel.getRemoteAddress() + "的消息: " + msg);
                //向其他的客户端转发消息
                forwardMsg(msg, channel);
            }
        } catch (IOException e) {
            System.out.println(channel.getRemoteAddress() + "离线了...");
            //取消注册，关闭通道
            key.cancel();
            channel.close();
        }
    }

    /**
     * 转发消息
     */
    private void forwardMsg(String msg, SocketChannel self) {
        Iterator<SelectionKey> iterator = selector.keys().iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            SelectableChannel channel = key.channel();
            if (channel instanceof SocketChannel && !channel.equals(self)) {
                SocketChannel targetChannel = (SocketChannel) channel;
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                try {
                    System.out.println("服务端转发消息");
                    targetChannel.write(byteBuffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new GroupChatServer();
    }

}
